package cn.ultrawise.view;

import java.util.ArrayList;

import cn.ultrawise.entity.EnemyPlane;
import cn.ultrawise.gameinterface.IView;
import cn.ultrawise.util.Map;
import android.content.Context;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameView extends SurfaceView implements IView {
	public static ArrayList<EnemyPlane> enemyPlanes = null;
	int tableWidth;
	int tableHeigh;
	GameViewBackGroundThread gameViewBackGroundThread;
	TutorialThread tutorialThread;

	public GameView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public GameView(Context context, int tableWidth, int tableHeigh) {
		super(context);
		this.tableWidth = tableWidth;
		this.tableHeigh = tableHeigh;
		initList();
		getHolder().addCallback(this);
		gameViewBackGroundThread = new GameViewBackGroundThread(this);
		gameViewBackGroundThread.setFlag(true);
		tutorialThread = new TutorialThread(70, this, getHolder());
		tutorialThread.setFlag(true);
		tutorialThread.start();
		gameViewBackGroundThread.start();
	}

	// 实现集合
	public void initList() {
		Map map = new Map(tableWidth, tableHeigh, this);
		enemyPlanes = map.getFirstPlane();
	}

	@Override
	public void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub

	}

	@Override
	public void initBitMap() {
		// TODO Auto-generated method stub

	}

	class TutorialThread extends Thread {
		private int span;// 休眠时间
		private GameView gameView;
		private boolean flag;
		private SurfaceHolder surfaceHolder;

		public TutorialThread(int span, GameView gameView,
				SurfaceHolder surfaceHolder) {
			super();
			this.span = span;
			this.gameView = gameView;
			this.surfaceHolder = surfaceHolder;
		}

		public boolean isFlag() {
			return flag;
		}

		public void setFlag(boolean flag) {
			this.flag = flag;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			Canvas canvas;
			while (isFlag()) {
				canvas = null;
				try {
					canvas = this.surfaceHolder.lockCanvas(null);
					synchronized (this.surfaceHolder) {
						gameView.onDraw(canvas);
					}
				} finally {
					if (canvas != null) {
						surfaceHolder.unlockCanvasAndPost(canvas);
					}
				}
				try {
					Thread.sleep(span);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
